package com.ruoyi.other.service.impl;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.baidu.AppUserAuth;
import com.ruoyi.common.baidu.AuthService;
import com.ruoyi.common.baidu.AuthUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.utils.CommonUtil;
import com.ruoyi.common.utils.HmacSha;
import com.ruoyi.common.utils.OrderNumberGeneratorUtil;
import com.ruoyi.common.utils.ProjectConstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.date.DateUtil;
import com.ruoyi.common.utils.date.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.parameter.QpsControlUtil;
import com.ruoyi.common.wx.GetOpenIdUtil;
import com.ruoyi.framework.security.auth.JWTUser;
import com.ruoyi.framework.security.auth.RequestContext;
import com.ruoyi.other.pojo.AppAgoraDTO;
import com.ruoyi.other.pojo.AppRongCloudDTO;
import com.ruoyi.other.pojo.AppUserLogoutDTO;
import com.ruoyi.other.pojo.AppUserThirdDTO;
import com.ruoyi.other.pojo.AppVoiceCallDTO;
import com.ruoyi.other.service.AppOtherService;
import com.ruoyi.system.domain.PriceSetting;
import com.ruoyi.system.mapper.PriceSettingMapper;
import com.ruoyi.thread.TaskAsync;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.UserCapitalFlow;
import com.ruoyi.user.domain.UserThirdParty;
import com.ruoyi.user.domain.UserTotalCapital;
import com.ruoyi.user.domain.UserVoiceCall;
import com.ruoyi.user.mapper.UserCapitalFlowMapper;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.mapper.UserVoiceCallMapper;
import com.ruoyi.user.pojo.AppGiftFlow;
import com.ruoyi.user.service.IUserThirdPartyService;
import com.ruoyi.user.service.IUserTotalCapitalService;

@Service
public class AppOtherServiceImpl implements AppOtherService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private PriceSettingMapper priceSettingMapper;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private IUserThirdPartyService userThirdPartyService;
	@Autowired
	private TaskAsync taskAsync;
	@Autowired
	private IUserTotalCapitalService userTotalCapitalService;
	@Autowired
	private UserCapitalFlowMapper userCapitalFlowMapper;
	@Autowired
	private UserVoiceCallMapper userVoiceCallMapper;
	@Autowired
	private GetOpenIdUtil getOpenIdUtil;


	/**
	 * 	获取用户ID
	 * @return
	 */
	private Long getLoginUserId() {
		Object object = RequestContext.get("userInfo");
		if(null == object) {
			return null;
		}
		JWTUser jwtUser = (JWTUser) object;
		if(null == jwtUser || null == jwtUser.getId()) {
			return null;
		}
		return jwtUser.getId();
	}

	@Override
	public AjaxResult confirmLogout(AppUserLogoutDTO userLogout, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			if(!redisUtil.setIfAbsentOnline("confirmLogout:"+loginUserId)) {
				return AjaxResult.error("休息一下呗~");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getPhone,User::getNickName));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			//			boolean right = false;
			//			Object savedMobile = redisUtil.get(ProjectConstant.RedisKey.MOBILE_CODE.getKeyPrefix() +"_"+ 4 + "_" + userLogout.getMobileCode());
			//			if (savedMobile != null && user.getPhone().equals(savedMobile.toString())) {
			//				right = true;
			//			}
			//			if("518186".equals(userLogout.getMobileCode())){
			//				right = true;
			//			}
			//			if (!right) {
			//				return AjaxResult.error("验证码不一致");
			//			}
			long nowLong = Long.parseLong(new SimpleDateFormat("ssSSS").format(new Date()));
			//修改手机号码和昵称
			user.setPhone(nowLong+"-"+user.getPhone());
			user.setNickName("已注销-"+user.getNickName()+"-"+Long.parseLong(new SimpleDateFormat("SSS").format(new Date())));
			user.setEnabled(4);
			user.setLogoutType(userLogout.getLogoutType());
			user.setLogoutContent(userLogout.getLogoutContent());
			user.setServiceType(DateUtils.format(DateUtils.addDateForDays(new Date(),1), "yyyyMMddHHmm"));
			userMapper.updateById(user);
			userThirdPartyService.remove(new LambdaQueryWrapper<UserThirdParty>().eq(UserThirdParty::getUserId, loginUserId));
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getLogoutType(HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			List<PriceSetting> list = priceSettingMapper.selectList(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "注销类型"));
			return AjaxResult.success(list.stream().map(PriceSetting::getPriceName).collect(Collectors.toList()));
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getAccountManage(HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			Map<String,Object> map = new HashMap<String,Object>();
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getPhone));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			map.put("phone", user.getPhone());
			int isWechat = 0;
			int isAlipay = 0;
			String alipayAccount = "";
			String alipayName = "";
			// 微信/ 支付宝 
			UserThirdParty third = userThirdPartyService.getOne(new LambdaQueryWrapper<UserThirdParty>().eq(UserThirdParty::getUserId, loginUserId));
			if(null != third) {
				if(StringUtils.isNotEmpty(third.getOpenId())) {
					isWechat = 1;
				}
				if(StringUtils.isNotEmpty(third.getAlipayAccount()) && StringUtils.isNotEmpty(third.getAlipayUserName())) {
					isAlipay = 1;
					alipayAccount = third.getAlipayAccount();
					alipayName = third.getAlipayUserName();
				}
			}
			map.put("isWechat", isWechat);
			map.put("isAlipay", isAlipay);
			map.put("alipayAccount", alipayAccount);
			map.put("alipayName", alipayName);
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult bindAlipay(AppUserThirdDTO userThird, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getPhone,User::getNickName));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			int count = userThirdPartyService.count(new LambdaQueryWrapper<UserThirdParty>().eq(UserThirdParty::getAlipayAccount, userThird.getAlipayAccount())
					.eq(UserThirdParty::getAlipayUserName, userThird.getAlipayUserName()));
			if(count > 0) {
				return  AjaxResult.error("此支付宝已绑定其他账号");
			}
			UserThirdParty third = userThirdPartyService.getOne(new LambdaQueryWrapper<UserThirdParty>().eq(UserThirdParty::getUserId, loginUserId));
			if(null != third) {
				third.setAlipayAccount(userThird.getAlipayAccount());
				third.setAlipayUserName(userThird.getAlipayUserName());
				userThirdPartyService.updateById(third);
			}else {
				third = new UserThirdParty();
				third.setUserId(loginUserId);
				third.setMobile(user.getPhone());
				third.setNickName(user.getNickName());
				third.setAlipayAccount(userThird.getAlipayAccount());
				third.setAlipayUserName(userThird.getAlipayUserName());
				userThirdPartyService.save(third);
			}
			return AjaxResult.success("支付宝绑定成功");
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult bindWechat(AppUserThirdDTO userThird, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getPhone,User::getNickName));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			UserThirdParty third = userThirdPartyService.getOne(new LambdaQueryWrapper<UserThirdParty>().eq(UserThirdParty::getUserId, loginUserId));
			if(null != third ) {
				if(StringUtils.isNotEmpty(third.getOpenId())) {
					return AjaxResult.error("已绑定微信");
				}
				third.setOpenId(getOpenIdUtil.getopenid2(userThird.getCode()));
				third.setUpdateTime(new Date());
				userThirdPartyService.updateById(third);
			}else {
				third = new UserThirdParty();
				third.setUserId(loginUserId);
				third.setMobile(user.getPhone());
				third.setNickName(user.getNickName());
				third.setOpenId(getOpenIdUtil.getopenid2(userThird.getCode()));
				third.setCreateTime(new Date());
				userThirdPartyService.save(third);
			}
			return AjaxResult.success("微信绑定成功");
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getRealNameToken(HttpServletRequest request) {
		try {
			Long userId = getLoginUserId();
			if(null == userId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			Map<String,Object> map = new HashMap<String,Object>();
			boolean flag = QpsControlUtil.getInstance().isPass(10);
			if (!flag) {
				Thread.sleep(500);
			}
			map = AuthService.getVerifyToken();
			if(!map.get("code").toString().equals("200")) {
				return AjaxResult.error("网络繁忙");
			}
			// 将token 存入缓存
			redisUtil.set(userId+"accessToken", map.get("accessToken"), 259200);
			redisUtil.set(userId+"verifyToken", map.get("verifyToken"), 259200);
			map.put("accessToken", "");
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult authPass(HttpServletRequest request) {
		try {
			Long userId = getLoginUserId();
			if(null == userId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			boolean flag = QpsControlUtil.getInstance().isPass(2);
			if (!flag) {
				Thread.sleep(500);
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userId).select(User::getId,User::getRealPersonAuth,User::getNickName,User::getPhone));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			if(1 == user.getRealPersonAuth()) {
				return AjaxResult.success("已认证");
			}
			Object accessToken = redisUtil.get(userId+"accessToken");
			Object verifyToken = redisUtil.get(userId+"verifyToken");
			if(Objects.isNull(accessToken) || Objects.isNull(verifyToken) ){
				return AjaxResult.error("认证失败");
			}
			user.setRealPersonAuth(1);
			//查询认证信息
			AppUserAuth userAuth = AuthService.resultDetail(accessToken.toString(), verifyToken.toString());
			if(null == userAuth) {
				return AjaxResult.error("认证未通过");
			}
			// 保存用户信息
			Date birthday = AuthUtil.getBirthday(userAuth);
			//user.setBackBirthday(birthday);
			user.setBirthday(birthday);
			user.setAge(CommonUtil.getAge(birthday));
			String sex = AuthUtil.getSex(userAuth);
			if(StringUtils.isNotEmpty(sex)) {
				user.setSex(sex);
			}
			//处理星座
			SimpleDateFormat df = new SimpleDateFormat("MM");
			SimpleDateFormat dfc = new SimpleDateFormat("dd");
			if(null != birthday) {
				user.setConstellation(DateUtil.constellation(Integer.valueOf(df.format(birthday)), Integer.valueOf(dfc.format(birthday))));
			}else {
				user.setConstellation(DateUtil.constellation(Integer.valueOf(df.format(new Date())), Integer.valueOf(dfc.format(new Date()))));
			}
			if(StringUtils.isNotEmpty(userAuth.getIdCard())) {
				user.setIdCard(userAuth.getIdCard());
			}
			if(StringUtils.isNotEmpty(userAuth.getName())) {
				user.setName(userAuth.getName());
			}
			userMapper.updateById(user);
			// 真人认证照片
			if(StringUtils.isNotEmpty(userAuth.getImage())) {
				redisUtil.del(userId+"accessToken");
				redisUtil.del(userId+"verifyToken");
				//解析认证结果
				taskAsync.analysisAuthResult(userId, userAuth.getImage());
			}
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult giveGift(Long toUserId, Long businessId, HttpServletRequest request) {
		try {
			Long userId = getLoginUserId();
			if(null == userId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getId, businessId)
					.select(PriceSetting::getId,PriceSetting::getCurrentPrice,PriceSetting::getPriceName));
			if(null == set) {
				return AjaxResult.error("礼物已被下架");
			}
			UserTotalCapital userTotalCapital = userTotalCapitalService.initData("3", userId);
			if(userTotalCapital == null) {
				return AjaxResult.error("余额不足");
			}
			if("1".equals(userTotalCapital.getIsAccountFrozen())) {
				return AjaxResult.error("账户已被冻结，请联系客户！原因："+userTotalCapital.getAccountFrozenExplain());
			}
			BigDecimal usable = userTotalCapital.getTotalAmount().subtract(userTotalCapital.getFrozenAmount());
			if(usable.compareTo(set.getCurrentPrice()) < 0) {
				return AjaxResult.error("余额不足");
			}
			// 修改余额				
			userTotalCapital.setTotalAmount(userTotalCapital.getTotalAmount().subtract(set.getCurrentPrice()));
			userTotalCapitalService.updateById(userTotalCapital);
			// 添加礼物流水
			UserCapitalFlow flow = new UserCapitalFlow();
			flow.setType(5);
			flow.setBusinessType(4);
			flow.setAmount(set.getCurrentPrice());
			flow.setUserId(userId);
			flow.setToUserId(toUserId);
			flow.setOrderNo(OrderNumberGeneratorUtil.get());
			flow.setIsSettle(0);
			flow.setSource(0);
			flow.setRelatedId(businessId);
			flow.setRemark("赠送礼物");
			flow.setNameType(set.getPriceName());
			userCapitalFlowMapper.insert(flow);
			// 对方收益增加- 获取礼物抽佣比例
			PriceSetting cset = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "gift_commission").select(PriceSetting::getId,
					PriceSetting::getCurrentPrice));
			BigDecimal commission = BigDecimal.valueOf(0.5);
			if(null != cset && null != cset.getCurrentPrice()) {
				commission = cset.getCurrentPrice();
			}
			BigDecimal multiply = set.getCurrentPrice().multiply(commission);
			userTotalCapitalService.initUserTotalCapital("1", toUserId, set.getCurrentPrice().subtract(multiply), 1);
			// 流水
			flow = new UserCapitalFlow();
			flow.setType(4);
			flow.setBusinessType(4);
			flow.setAmount(set.getCurrentPrice().subtract(multiply));
			flow.setUserId(toUserId);
			flow.setToUserId(userId);
			flow.setOrderNo(OrderNumberGeneratorUtil.get());
			flow.setIsSettle(0);
			flow.setSource(0);
			flow.setRelatedId(businessId);
			flow.setRemark("收到礼物");
			flow.setNameType(set.getPriceName());
			userCapitalFlowMapper.insert(flow);
			// 发送赠送礼物消息
			taskAsync.sendSystemMsg(toUserId, userId, 2, "", "");
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult giveGiftFlow(Integer pageNo, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			//pageNo = (pageNo -1)*10;
			IPage<AppGiftFlow> list = userCapitalFlowMapper.giftFlowList(new Page<AppGiftFlow>().setCurrent(pageNo).setSize(20), loginUserId, 5,4);
			list.getRecords().stream().forEach(flow ->{
				flow.setAmount(new BigDecimal(flow.getAmount().stripTrailingZeros().toPlainString()));
			});
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("list", list.getRecords());
			map.put("total", list.getTotal());
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult receiveGiftFlow(Integer pageNo, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			//pageNo = (pageNo -1)*10;
			IPage<AppGiftFlow> list = userCapitalFlowMapper.giftFlowList(new Page<AppGiftFlow>().setCurrent(pageNo).setSize(20), loginUserId, 4,4);
			list.getRecords().stream().forEach(flow ->{
				flow.setAmount(new BigDecimal(flow.getAmount().stripTrailingZeros().toPlainString()));
			});
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("list", list.getRecords());
			map.put("total", list.getTotal());
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult notifyAgora(String payload) {
		AppAgoraDTO agora = JSONObject.parseObject(payload, AppAgoraDTO.class);
		if(null == agora) {
			return AjaxResult.error();
		}

		return AjaxResult.success();
	}


	@Override
	public AjaxResult updVoiceCallStatus(AppVoiceCallDTO call, HttpServletRequest request) {
		// 1=通话中 3=已拒绝 4=未接通 5=已取消 
		if(1 == call.getStatus()) {
			UserVoiceCall voice = userVoiceCallMapper.selectOne(new LambdaQueryWrapper<UserVoiceCall>().eq(UserVoiceCall::getRoomId, call.getRoomId()).eq(UserVoiceCall::getUserId, call.getUserId())
					.eq(UserVoiceCall::getToUserId, call.getToUserId()));
			if(null == voice) {
				voice = new UserVoiceCall();
				voice.setUserId(call.getUserId());
				voice.setToUserId(call.getToUserId());
				voice.setStatus(call.getStatus());
				voice.setRoomId(call.getRoomId());
				voice.setBegTime(new Date());
				voice.setRemark("通话中");
				userVoiceCallMapper.insert(voice);
				System.out.println("添加成功");
				// 计算余额能够打多长时间的通话
				taskAsync.computeAmount(voice.getId(),call.getUserId(),call.getRoomId(),call.getToUserId());
				// 更新用户状态
				taskAsync.updateUserBusy(call.getUserId(), call.getToUserId(), 1);
			}else {
				voice.setStatus(call.getStatus());
				voice.setBegTime(new Date());
				userVoiceCallMapper.updateById(voice);
				// 更新用户状态
				taskAsync.updateUserBusy(call.getUserId(), call.getToUserId(), 1);
				System.out.println("修改成功");
			}
		}else {
			String remark = "";
			switch (call.getStatus()) {
			case 3:
				remark = "已拒绝";
				break;
			case 4:
				User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, call.getUserId()).select(User::getId,User::getNickName));
				String nickName = "用户";
				if(null != user && StringUtils.isNotEmpty(user.getNickName())) {
					nickName = user.getNickName();
				}
				taskAsync.sendSystemMsg(call.getToUserId(), 0l, 18, "连麦提醒",nickName+"在"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm")+"给您发起了连麦未接通，请及时回复！");
				remark = "未接通";
				break;
			case 5:
				remark = "已取消";
				break;
			case 6:
				remark = "网络异常";
				user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, call.getUserId()).select(User::getId,User::getNickName));
				nickName = "用户";
				if(null != user && StringUtils.isNotEmpty(user.getNickName())) {
					nickName = user.getNickName();
				}
				taskAsync.sendSystemMsg(call.getToUserId(), 0l, 18, "连麦提醒","您与"+nickName+"用户通话已经中断，请检查您的网络状态！");

				remark = "网络异常";
				user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, call.getToUserId()).select(User::getId,User::getNickName));
				nickName = "咨询师";
				if(null != user && StringUtils.isNotEmpty(user.getNickName())) {
					nickName = user.getNickName();
				}
				taskAsync.sendSystemMsg(call.getUserId(), 0l, 18, "连麦提醒","您与"+nickName+"咨询师通话已经中断，请检查您的网络状态！");
				break;
			default:
				break;
			}
			UserVoiceCall voice = new UserVoiceCall();
			voice = new UserVoiceCall();
			voice.setUserId(call.getUserId());
			voice.setToUserId(call.getToUserId());
			voice.setStatus(call.getStatus());
			voice.setRoomId(call.getRoomId());
			voice.setRemark(remark);
			userVoiceCallMapper.insert(voice);
		}
		return AjaxResult.success();
	}

	@Override
	public AjaxResult getUserToken(HttpServletRequest request) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		try {
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getNickName));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			if(StringUtils.isEmpty(user.getNickName())) user.setNickName("似水年华");
			if(redisUtil.hasKey(ProjectConstant.RONG_CLOUD_REDIS_KEY+loginUserId)) {
				Object obj = redisUtil.get(ProjectConstant.RONG_CLOUD_REDIS_KEY+loginUserId);
				if(null != obj) {
					return AjaxResult.success("成功",obj.toString());
				}
			}
			String nonce = OrderNumberGeneratorUtil.get();
			String timestamp = System.currentTimeMillis()+"";
			String signature = HmacSha.shaEncode(ProjectConstant.RONG_CLOUD_APP_SECRET+nonce+timestamp);
			System.out.println(signature);
			List<NameValuePair> form = new ArrayList<>();
			form.add(new BasicNameValuePair("userId", String.valueOf(loginUserId)));
			form.add(new BasicNameValuePair("name", user.getNickName()));
			String result = HttpUtils.postUrlencodedRongCloud(form, ProjectConstant.RONG_CLOUD_GET_USER_TOKEN, nonce, timestamp, signature);
			JSONObject resultJson = JSONObject.parseObject(result);
			int code = resultJson.getIntValue("code");
			if(200 == code) {
				String token = resultJson.getString("token");
				redisUtil.set(ProjectConstant.RONG_CLOUD_REDIS_KEY+loginUserId, token);
				return AjaxResult.success("获取成功",token);
			}else {
				return AjaxResult.error("获取失败:"+code);
			}
			// {"code":200,"userId":"1209","token":"KJhxWVEGm9zwSJlvaScP5v5FYHAaF0Ed5dcKygJyHBI=@2yo5.cn.rongnav.com;2yo5.cn.rongcfg.com"}
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}

	}

	public static void main(String[] args) throws Exception {
		//		String nonce = OrderNumberGeneratorUtil.get();
		//		String timestamp = System.currentTimeMillis()+"";
		//		String signature = HmacSha.shaEncode(ProjectConstant.RONG_CLOUD_APP_SECRET+nonce+timestamp);
		//		System.out.println(signature);
		//		List<NameValuePair> form = new ArrayList<>();
		//		form.add(new BasicNameValuePair("userId", String.valueOf(1209)));
		//		form.add(new BasicNameValuePair("name", "哦哦哦"));
		//		String postUrlencodedRongCloud = HttpUtils.postUrlencodedRongCloud(form, ProjectConstant.RONG_CLOUD_GET_USER_TOKEN, nonce, timestamp, signature);
		//		System.out.println(postUrlencodedRongCloud);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long l = 1692240373172l;
		String format = sdf.format(l);
		System.out.println("日期格式："+format);
	}

	@Override
	public AjaxResult notifyRongCloud(String payload) {
		AppRongCloudDTO rc = JSONObject.parseObject(payload, AppRongCloudDTO.class);
		if(null == rc) {
			return AjaxResult.error();
		}
		// 房间销毁
		if(3 == rc.getEvent()) {
			UserVoiceCall voice = userVoiceCallMapper.selectOne(new LambdaQueryWrapper<UserVoiceCall>().eq(UserVoiceCall::getRoomId, rc.getRoomId()));
			if(null != voice && 1 == voice.getStatus()) {
				voice.setSid(rc.getSessionId());
				voice.setExtend(String.valueOf(rc.getDurationTime()));
				voice.setExtend2(payload);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				voice.setEndTime(DateUtils.stringToDate(sdf.format(rc.getTimestamp()), "yyyy-MM-dd HH:mm:ss"));
				voice.setRemark("已结束");
				voice.setStatus(2);
				userVoiceCallMapper.updateById(voice);
				// 结算
				taskAsync.settlementVoiceCall(voice);
				// 更新用户状态
				taskAsync.updateUserBusy(voice.getUserId(), voice.getToUserId(), 0);
			}
		}
		return AjaxResult.success();
	}

	@Override
	public AjaxResult sendVoiceCallCheck(Integer toUserId,HttpServletRequest request) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		UserTotalCapital total = userTotalCapitalService.getOne(new LambdaQueryWrapper<UserTotalCapital>().eq(UserTotalCapital::getUserId, loginUserId).eq(UserTotalCapital::getAmountType, 3));
		if(null == total || total.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0) {
			return AjaxResult.error(500168,"余额不足,请先充值");
		}
		// 计算每分钟金额
		BigDecimal amount = new BigDecimal("10");
		PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "voiceCoallMinPrice"));
		if(null != set && null != set.getCurrentPrice()) {
			amount = set.getCurrentPrice();
		}
		if(total.getTotalAmount().compareTo(amount) <= 0) {
			return AjaxResult.error(500168,"余额不足,请先充值");
		}
		if(null != toUserId) {
			// 计算每分钟金额
			BigDecimal minAmount = new BigDecimal("3");
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, toUserId).select(User::getId,User::getPrice));
			if(null != user && null != user.getPrice()) {
				minAmount = user.getPrice();
			}
			BigDecimal divide = total.getTotalAmount().divide(minAmount);
			int minute = divide.intValue();
			if(minute <= 5) {
				return AjaxResult.error(500168,"余额不足,请先充值");
			}
		}
		return AjaxResult.success();
	}
}
